import pymongo

from db import contents_col, book_col


def convert_book(book):
    page = 0
    c = contents_col.find({'$and': [{'book': book['_id']}, {'texts': {'$ne': []}}]}).sort('order',
                                                                                          pymongo.ASCENDING).limit(10)
    chapters = list(c)
    with open(f'./books/{book['title']}.txt', 'w', encoding='utf-8') as f:
        while chapters:
            for c in chapters:
                lines = c['texts']
                f.write(f'\n\n{c["title"]}\n')
                for line in lines:
                    f.write('\n\t' + line + '\n')
                print(f'{c['title']}\t写入成功')
            page += 1
            c = contents_col.find({'$and': [{'book': book['_id']}, {'texts': {'$ne': []}}]}).sort('order',
                                                                                                  pymongo.ASCENDING).skip(page*10).limit(10)
            chapters = list(c)


if __name__ == '__main__':
    book_name = input('请输入小说名称:').strip()
    if book_name:
        cursor = book_col.find({'title': book_name})
        books = list(cursor)
        book = None
        if not books:
            print(f"没有找到名称为“{book_name}”的小说")
        elif len(books) > 1:
            print(f'找到多本名称为“{book_name}”的小说,请选择:')
            for i, book in enumerate(books):
                print(f'{i + 1}\t{book['title']}(作者:{book['author']})')
            num = 0
            while num not in range(1, len(books)):
                num = input("刷入要转换的序号:\t")
            book = books[num - 1]
            convert_book(book)
        else:
            book = books[0]
            convert_book(book)
